<template>
  <a-spin :spinning="isLoading" tip="数据加载中">
    <div class="call-overview">
      <div class="header-section">
        <div class="title">API调用概况</div>
        <div class="filter-box">
          <a-range-picker
            v-model:value="rangeValue"
            :allow-clear="false"
            style="width: 216px; height: 36px"
            value-format="YYYY-MM-DD"
            @change="onRangeChange"
          />
          <a-divider type="vertical" style="height: 20px" />

          <a-select
            ref="select"
            v-model:value="pageForm.algorithmId"
            placeholder="请选择"
            style="width: 140px"
            class="mr-8"
            :options="algorithmIdOptions"
            :field-names="{ label: 'name', value: 'id' }"
            @change="init()"
          />
        </div>
      </div>

      <div class="ratio-section">
        <div class="ratio-total ratio-item">
          <div class="label z-99">调用总量</div>
          <div class="value z-99">{{ recordData.total }}</div>
        </div>
        <div class="ratio-failed ratio-item" :style="{ '--failed-width': styleAttr['--failed-width'] }">
          <div class="label z-99">调用失败率</div>
          <div class="value z-99">{{ styleAttr['--failed-width'] }}</div>
        </div>
      </div>

      <div id="main" class="echarts-item"></div>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
  import dayjs from 'dayjs'
  import * as echarts from 'echarts'
  import { dateFormat } from 'g6-fn'
  import { onMounted, ref } from 'vue'

  import { callRecordsApi } from '@/services/api'

  const isLoading = ref<boolean>(false)

  // 调用失败率
  const styleAttr = { '--failed-width': '' }
  // 时间
  const SEVEN_DAY = 6 * 24 * 60 * 60 * 1000 // 七天的毫秒数

  const rangeValue = ref<any>([dayjs(Date.now() - SEVEN_DAY), dayjs(Date.now())])
  // 算法服务
  const algorithmIdOptions = ref<Record<string, any>[]>([{ name: '全部算法服务', id: '' }])
  const pageForm = ref<Record<string, string | number | undefined | [string, string]>>({
    algorithmId: '',
    versionId: '',
    appId: '',
    callTimeStart: dateFormat(rangeValue.value[0], 'YYYY-MM-DD 00:00:00'),
    callTimeEnd: dateFormat(rangeValue.value[1], 'YYYY-MM-DD 23:59:59')
  })
  // 获取算法
  const getAlVersionList = async (): Promise<void> => {
    // 获取算法
    const { data } = await callRecordsApi.getAlVersionList()

    algorithmIdOptions.value = [...algorithmIdOptions.value, ...data.map((item: any) => ({ name: item.name, id: item.id }))]
  }

  // 文件数量趋势
  let fileTrendCloudDom
  let fileTrendCloudChart: any
  const fileTrendCloudInit = (): void => {
    const option = {
      tooltip: {
        trigger: 'axis', // 设置 tooltip 的触发方式为 axis
        // 使用 formatter 自定义 tooltip 的内容
        formatter: function (params: any) {
          let tooltipContent =
            '<div style="display: flex; justify-content: center; width: 120px;  background: #fff;  border-radius:2px;  box-shadow: 0 1px 2px 0 rgba(2, 36, 59, 0.03); flex-direction: column;">'
          tooltipContent += params[0].axisValue // 用于存储自定义的 tooltip 内容
          tooltipContent += '<div style="text-align: left;width:120px;height:74px">' // 自定义样式，可以根据需要修改

          // 循环遍历每个数据项，显示每个数据点的信息
          // let seriesName = '2020/' + params // 获取系列名称
          for (let i = 0; i < params.length; i++) {
            let value = params[i].value // 获取数据点的值

            tooltipContent += '<div style="font-size:12px;color: rgba(100, 154, 240, 1);margin-bottom:8px">' + '</div>' // 显示系列名称

            // 判断当前数据点是否是被鼠标指的那条线上的数据点，如果是，则添加特殊的圆点标识
            if (params[i].seriesName === '调用次数') {
              tooltipContent +=
                '<div style="margin-right: 5px; display: inline-block; width: 8px; height: 8px; border-radius: 50%; background-color: rgba(100, 154, 240, 1);"></div>' // 显示特殊的圆点标识
            } else if (params[i].seriesName === '失败次数') {
              tooltipContent +=
                '<div style="margin-right: 5px; display: inline-block; width: 8px; height: 8px; border-radius: 50%; background-color: rgba(237, 132, 118, 1);"></div>'
            }

            tooltipContent +=
              '<div style="display:inline-block;font-size:12px">' +
              params[i].seriesName +
              ': ' +
              '<span style="margin-left: 40px;font-size: 12px; color: rgba(21, 23, 27, 0.95); font-weight: 600">' +
              value +
              '</span>' +
              '</div>' // 显示数据点的值
          }

          tooltipContent += '</div>' // 结束自定义样式
          console.log('=====', tooltipContent)

          return tooltipContent // 返回自定义的 tooltip 内容
        },
        padding: [8, 12, 8, 12],
        extraCssText: 'box-shadow: 0 0 1px rgba(0, 0, 0, 0.3);'
      },
      legend: {
        data: ['调用次数', '失败次数'],
        right: '0px',
        top: '0px',
        bottom: '0',
        icon: 'circle',
        itemWidth: 6,
        itemHeight: 6
      },

      grid: {
        bottom: '0%',
        left: '20px',
        right: '0px',
        height: '90%',
        width: '92%',
        containLabel: true
      },

      xAxis: {
        boundaryGap: false,
        type: 'category',
        data: recordData.value.brokenLineList.map(
          (item: { callTime: string; total: string; failed: number; succeed: number }) => item.callTime
        ),

        axisLine: {
          show: false
        },
        axisLabel: {
          color: 'rgba(17, 22, 31, 0.52)',
          marginLeft: 20
        },
        axisTick: {
          // alignWithLabel: true, // 将刻度线与文字对齐
          length: 4, // 刻度线的长度
          lineStyle: {
            color: 'rgba(217, 218, 219, 1)'
          }
        }
      },
      yAxis: {
        type: 'value',
        splitNumber: 5,
        axisTick: {
          show: false
        },

        axisLabel: {
          color: 'rgba(17, 22, 31, 0.52)'
        }
      },
      series: [
        {
          name: '调用次数',
          // stack: 'Total',
          type: 'line',
          lineStyle: {
            color: 'rgba(100, 154, 240, 1)'
          },
          itemStyle: {
            color: 'rgba(100, 154, 240, 1)'
          },
          legendHoverLink: false,
          symbol: 'circle', // 将符号设置为圆点
          symbolSize: 3, // 设置圆点大小
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(100, 154, 240, 0.40)'
              },
              {
                offset: 1,
                color: 'rgba(100, 154, 240, 0.10)'
              }
            ])
          },
          showSymbol: false, // 设置未移入时不显示圆点
          emphasis: {
            focus: 'series' // 设置触发效果为移入时显示圆点
          },
          data: recordData.value.brokenLineList.map(
            (item: { callTime: string; total: string; failed: number; succeed: number }) => item.total
          )
        },
        {
          name: '失败次数',
          type: 'line',
          // stack: 'Total',
          symbolSize: 6, // 设置圆点大小
          symbol: 'circle',
          lineStyle: {
            color: 'rgba(237, 132, 118, 1)'
          },
          itemStyle: {
            color: 'rgba(237, 132, 118, 1)'
          },
          showSymbol: false, // 设置未移入时不显示圆点
          emphasis: {
            focus: 'series' // 设置触发效果为移入时显示圆点
          },
          data: recordData.value.brokenLineList.map(
            (item: { callTime: string; total: string; failed: number; succeed: number }) => item.failed
          )
        }
      ]
    }

    option && fileTrendCloudChart.setOption(option)
  }
  const domInit = (): void => {
    fileTrendCloudDom = document.getElementById('main')
    fileTrendCloudChart = echarts.init(fileTrendCloudDom)
  }

  // 初始化
  const recordData = ref<Record<string, any>>({})

  // 时间处理
  const onRangeChange = (e: any) => {
    if (e) {
      console.log('e:', e)

      pageForm.value.callTimeStart = dateFormat(e[0], 'YYYY-MM-DD 00:00:00')
      pageForm.value.callTimeEnd = dateFormat(e[1], 'YYYY-MM-DD 23:59:59')
      init()
    }
  }
  const init = async (): Promise<void> => {
    isLoading.value = true
    const { data } = await callRecordsApi.queryCallRecords(pageForm.value as Record<string, string>)
    recordData.value = data
    // 失败率
    const re = Number(((Number(recordData.value.failed) / Number(recordData.value.total)) * 100).toFixed(2))
    styleAttr['--failed-width'] = re ? re + '%' : 0 + '%'
    domInit()
    await fileTrendCloudInit()
    isLoading.value = false
  }
  onMounted(async () => {
    await getAlVersionList()
    await init()
  })
</script>

<style lang="less" scoped>
  .call-overview {
    display: flex;
    align-items: flex-start;
    padding: 32px;
    background: #fff;
    border: 1px solid @border1;
    border-radius: 10px;
    flex-direction: column;
    gap: 24px;

    .header-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 946px;

      .title {
        font-size: 16px;
        font-style: normal;
        font-weight: 700;
        color: @text01;
      }
    }

    .ratio-section {
      display: flex;
      align-items: flex-start;
      height: 56px;
      gap: 32px;
      align-self: stretch;

      .ratio-item {
        display: flex;
        align-items: center;
        padding: 20px;
        gap: 32px;
        flex: 1 0 0;
        align-self: stretch;

        .label {
          margin-right: 32px;
          width: 80px;
          font-size: 16px;
          color: @text01;
          line-height: 24px;
        }

        .value {
          font-size: 24px;
          font-style: normal;
          line-height: 24px;
          font-weight: 700;
        }
      }

      .ratio-total {
        background: rgba(17, 103, 240, 0.04);
      }

      .ratio-failed {
        position: relative;
        background: rgba(250, 250, 250, 1);

        &::before {
          position: absolute;
          top: 0;
          right: 0;
          content: '';
          display: inline-block;
          width: var(--failed-width);
          height: 56px;
          background: rgba(237, 132, 118, 1);
        }
      }
    }

    .echarts-item {
      margin-top: 20px;
      width: 946px;
      height: 225px;
    }
  }
</style>
